 <template>
  <div class="eleMap">
    <div id="viewDiv">
      <div class="setPoint" title="画点">
        <span class="action-button esri-icon-polyline esri-widget-button esri-widget esri-interactive" id="polylineButton" type="button"
                title="画安保路线"></span>
      </div>
    </div>
  </div>
</template>

<script>
  import * as esriLoader from 'esri-loader';

  export default {
    name: 'lineMap',
    props:{
      lineSymbolColor: {
        type: String,
        default: '#8A2BE2'
      },
      lineSymbolWidth: {
        type: String,
        default: '4'
      },
      lineSymbolStyle: {
        type: String,
        default: 'solid' // solid： 实线 ； dash： 虚线
      },
      paths: Array,
    },
    data () {
      return {
        view: null,
        pointGraphic: null,
        tempGraphicsLayer: null, // 临时图形存放layer
        graphicData: null,       // 圈得存放数据
      }
    },
    created (){
      esriLoader.loadCss(cssURL);
    },
    mounted () {
      this.createMap();
    },

    methods: {
      createMap () {
        // 引入依赖
        esriLoader.loadModules([
          'esri/Map',
          'esri/views/MapView',
          'esri/layers/GraphicsLayer',
          'esri/widgets/Sketch/SketchViewModel',
          "esri/geometry/geometryEngine",
          "esri/geometry/Point",
          "esri/geometry/Polyline",
          'esri/layers/TileLayer',
          "esri/Basemap",
          'esri/Graphic'
        ], {url:dojoURL}).then(([EsriMap, MapView, GraphicsLayer, SketchViewModel, geometryEngine, Point, Polyline, TileLayer, Basemap, Graphic]) => {
          let self = this;
          var layer = new TileLayer({
            url:mapServer
          })
          var customBasemap = new Basemap({
            baseLayers: [layer],
          })

          this.map = new EsriMap({
            basemap: customBasemap
          })


          let updateGraphic
          self.tempGraphicsLayer = new GraphicsLayer()
          this.map.add(self.tempGraphicsLayer, 1)
          let view = new MapView({
            container: 'viewDiv',
            // center: [114.21868761726246, 30.584733852070247],
            center: g_centerPoint,
            zoom: 5,
            map: this.map
          })
         let pointSymbol = { // symbol used for points
           type: 'simple-marker', // autocasts as new SimpleMarkerSymbol()
           style: 'square',
           color: '#8A2BE2',
           size: '20px',
           outline: { // autocasts as new SimpleLineSymbol()
             color: [255, 255, 255],
             width: 3 // points
           }
         }


          // edit
          if(this.paths){
            let geometry = new Polyline({
              hasZ: false,
              hasM: true,
              paths: this.paths,
              spatialReference: { wkid: 4326 }
            })
            // 修改中心点
            view.center = this.paths[0][this.paths[0].length-1];
            DrawGeometry(geometry)
          }
          view.when(function (evt) {
            let sketchViewModel = new SketchViewModel({
              view: view,
              layer: self.tempGraphicsLayer,
              pointSymbol: pointSymbol,
            })

            setUpClickHandler()
            sketchViewModel.on('draw-complete', addGraphic)
            sketchViewModel.on('update-complete', addGraphic)
            sketchViewModel.on('update-cancel', addGraphic)
            let drawpolylineSymbol = document.getElementById('polylineButton')
            clickButton(drawpolylineSymbol, 'polyline')
            function clickButton (button, type) {
              button.onclick = function () {
                view.graphics.removeAll();
                sketchViewModel.reset()
                self.tempGraphicsLayer.removeAll()
                sketchViewModel.create(type)
                setActiveButton(this)
              }
            }
            function setActiveButton (selectedButton) {
              // focus the view to activete keyboard shortcuts for sketching
              view.focus()
              let elements = document.getElementsByClassName('active')
              for (let i = 0; i < elements.length; i++) {
                elements[i].classList.remove('active')
              }
              if (selectedButton) {
                selectedButton.classList.add('active')
              }
            }
            function setUpClickHandler () {
              view.on('click', function (evt) {
                /*view.hitTest(evt).then(function (response) {
                  let results = response.results
                  if (results.length && results[results.length - 1].graphic) {
                    if (!updateGraphic) {
                      updateGraphic = results[results.length - 1].graphic
                      self.tempGraphicsLayer.remove(updateGraphic)
                      sketchViewModel.update(updateGraphic.geometry)
                    }
                  }
                })*/
              })
            }
          })
          function addGraphic (evt) {
            let geometry = evt.geometry
            DrawGeometry(geometry)
          }
          function DrawGeometry(geometry) {
            let symbol
            let polylineSymbol = {
              type: 'simple-line', // autocasts as new SimpleLineSymbol()
              color: self.lineSymbolColor,
              // color: '#8A2BE2',
              width: self.lineSymbolWidth,
              // width: '4',
              style: self.lineSymbolStyle
              // style: 'solid'
            }
            if (geometry.type === 'polyline') {
              symbol = polylineSymbol
            }
            let graphic = new Graphic({
              geometry: geometry,
              symbol: symbol
            })
            self.tempGraphicsLayer.add(graphic)
            self.graphicData = graphic;

//            //console.log(self.tempGraphicsLayer)
            var json = graphic.toJSON();

            self.$emit('graphicJSON', json)

            //console.log(JSON.stringify(json));
            updateGraphic = null
            if (geometry.type === 'polyline') {
                var lineLength = geometryEngine.geodesicLength(geometry, 'kilometers');
                //console.log(lineLength)
                // Create a symbol for drawing the point
                var textSymbol = {
                  type: "text", // autocasts as new TextSymbol()
                  color: "#ff0000",
                  text: lineLength.toFixed(1) + '公里', //
                  xoffset: -30,
                  yoffset: -30,
                  font: { // autocasts as new Font()
                    size: 16,
                    weight: "bold",
                    family: "CalciteWebCoreIcons"
                  }
                };
              var firstPointAry = json.geometry.paths[0][0];
              var lastPointAry = json.geometry.paths[0][json.geometry.paths[0].length - 1];
              // First create a point geometry
              var firstPoint = new Point({
                longitude: firstPointAry[0],
                latitude: firstPointAry[1]
              })
              var lastPoint = new Point({
                longitude: lastPointAry[0],
                latitude: lastPointAry[1]
              });
              var textPoint = new Point({
                longitude: lastPointAry[0],
                latitude: lastPointAry[1]
              });
              // Create a graphic and add the geometry and symbol to it
              var starSymbol = {
                type: 'picture-marker', // autocasts as new PictureMarkerSymbol()
                url:  'static/img/start_point.png',
                width: '40px',
                height: '40px',
                xoffset: 0,
                yoffset: 18,
              }
              var endSymbol = {
                type: 'picture-marker',
                url: 'static/img/end_point.png',
                width: '40px',
                height: '40px',
                xoffset: 0,
                yoffset: 18,
              }
              var firstGraphic = new Graphic({
                geometry: firstPoint,
                symbol: starSymbol
              })
              var endGraphic = new Graphic({
                geometry: lastPoint,
                symbol: endSymbol
              })
              var textGraphic = new Graphic({
                geometry: textPoint,
                symbol: textSymbol
              });
              // Add the graphics to the view's graphics layer
              view.graphics.addMany([firstGraphic, endGraphic, textGraphic]);
            }
          }

        })
      },
      // 改变圈边线颜色
      changeOutline(){
        let self = this;
        self.tempGraphicsLayer.remove(self.graphicData);
        self.graphicData.symbol.color = self.lineSymbolColor;
        self.graphicData.symbol.width = self.lineSymbolWidth;
        self.graphicData.symbol.style = self.lineSymbolStyle;
        this.$nextTick(function(){
          self.tempGraphicsLayer.add(self.graphicData);
        })
      }
    },// end methods
    watch:{
      paths: {
        handler: function () {
          this.createMap();
        },
        deep: true
      },
      lineSymbolColor(){
        if( this.graphicData ){
          this.changeOutline();
        }
      },
      lineSymbolWidth(){
        if( this.graphicData ){
          this.changeOutline();
        }
      },
      lineSymbolStyle(){
        if( this.graphicData ){
          this.changeOutline();
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  .eleMap {
    width: 100%;
    height: 100%;
  }
  #viewDiv {
    width: 100%;
    height: 100%;
    z-index: -1;
  }
  .action-button {
    font-size: 16px;
    background-color: white;
    border: 1px solid #D3D3D3;
    color: #6e6e6e;
    height: 32px;
    width: 32px;
    text-align: center;
    box-shadow: 0 0 1px rgba(0, 0, 0, 0.3);
  }

  .action-button:hover,
  .action-button:focus {
    background: #0079c1;
    color: #e4e4e4;
  }
  .setPoint{
    position: absolute;
    top: 79px;
    left: 14px;
    z-index: 100;
  }

</style>
